<template>
    <div @click="treeBlurHide" class="calendar-page">
        <el-row >
            <el-col class="my-calendar" :span="16" :offset="4">
                <div class="calendar-wraper">
                    <el-form v-model="filter" :inline="true"  class="">
                        <el-row>
                            <el-col :span="22">
                                <el-form-item label="运营员:">
                                    <el-input :disabled="true" v-show="readOnly" placeholder="请选择运营员" v-model="seller" size="small"></el-input>
                                    <el-input v-show="!readOnly" readonly placeholder="请选择运营员" v-model="seller" size="small" @focus="getOwnerData" icon="el-icon-search"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="1" style="margin-left: -54px;">
                                <el-button class="calendar-search" @click="filterCustomerCalendar(currentYear,currentMonth)" size="small" type="primary" icon="el-icon-search">查询</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div class="calendar-menu">
                        <el-button @click="pickPre(currentYear,currentMonth)" size="small" type="primary" style="margin: 0 15px 0 0"><i class="fa fa-chevron-left"></i> 上一月</el-button>
                        <el-button @click="pickToday" size="small" type="primary" style="margin: 0 15px 0 0" icon="el-icon-time">今天</el-button>
                        <el-button @click="pickNext(currentYear,currentMonth)"  size="small" type="primary" style="margin: 0 15px 0 0">下一月 <i class="fa fa-chevron-right"></i></el-button>
                        <span class="calendar-menu-name">紧急</span><span class="calendar-menu-block"></span>
                        <span class="calendar-menu-name">全部</span><span class="calendar-menu-block all"></span>
                    </div>
                    <el-row>
                        <el-col class="calendar-table" :span="24"  justify="center">
                            <ul class="calendar-head">
                                <li>周一</li>
                                <li>周二</li>
                                <li>周三</li>
                                <li>周四</li>
                                <li>周五</li>
                                <li>周六</li>
                                <li>周日</li>
                            </ul>
                            <ul class="calendar-body">
                                <li class="calendar-row" v-for="day in days">
                                    <span :class="{otherMonth: isOtherMonth(day),today: isToday(day)}">{{day.date}}</span>
                                    <div class="countCon">
                                        <nuxt-link v-if="day.allRecordCount != 0" :to="{path:'../brandadmin/calend',query:{year:day.year,month:day.month,date:day.date,CustomerLevels: filter.levels,LevelsName:category.name,usIds: usIdString,bname:bnameString,calendarFlag:1}}">
                                            <div :class="{full: !day.energencyCount}" class="todoList">{{day.allRecordCount}}</div>
                                        </nuxt-link>
                                        <nuxt-link v-if="day.energencyCount != 0" :to="{path:'../brandadmin/calend',query:{year:day.year,month:day.month,date:day.date,CustomerLevels:'',LevelsName:'1',usIds: usIdString,bname:bnameString,calendarFlag:1}}">
                                            <div class="todoList2">{{day.energencyCount}}</div>
                                        </nuxt-link>
                                    </div>

                                </li>
                            </ul>
                        </el-col>
                    </el-row>
                    <el-row>
                        <div class="calendar-tip">只显示当月数据：<span style="color: #666">{{currentYear}}-{{currentMonth}}</span></div>
                    </el-row>
                </div>
            </el-col>
        </el-row>
        <!--*****************运营员框************-->
        <el-dialog title="选择运营员" :visible.sync="dialogVisible" @close="closeOwnerDialog">
            <el-row style="margin-bottom: 20px" >
                <el-col :span="12">
                    <el-select v-model="ownerFilter.deptId" @change="searchOwner" placeholder="请选择部门" size="small">
                        <el-option
                                v-for="(item,index) in ownerOptions"
                                :key="index"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
                <!--<el-col :span="12">
                    <el-button type="primary"  @click="searchOwner" size="small"><i class="fa fa-search"></i> 查询</el-button>
                </el-col>-->
            </el-row>
            <el-table
                    ref="ownerMultipleTable"
                    :data="ownerData"
                    border
                    style="width: 100% max-height:541px"
                    highlight-current-row
                    @selection-change="handleOwnerSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="account" label="用户名" width="" align="center"></el-table-column>
                <el-table-column prop="name" label="用户姓名" align="center"></el-table-column>
                <el-table-column prop="departmentName" label="部门" align="center"></el-table-column>
            </el-table>
            <el-row class="paging">
                <el-pagination
                        @current-change="ownerHandleCurrentChange"
                        @size-change="ownerHandleSizeChange"
                        :current-page="ownerPage.pageNum"
                        :page-sizes="ownerPage.pageSizes"
                        :page-size="10"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="ownerPage.total">
                </el-pagination>
            </el-row>

            <el-row style="margin-top: 20px;text-align: center" >
                <el-col :span="12">
                    <el-button type="primary" class="top_save" @click="onSubmit" size="small"><i class="fa fa-save"></i> 保存</el-button>
                </el-col>
                <el-col :span="12">
                    <el-button type="danger" class="top_close" @click="cancelSeller"  size="small"><i class="fa fa-sign-out"></i> 取消</el-button>
                </el-col>
            </el-row>
        </el-dialog>
    </div>

</template>

<script>
    import Vue from 'vue'
    import { mapGetters,mapActions,mapMutations } from 'vuex'
    import { Row,Col,Button,Input,Select,Option,FormItem,Form,Table,TableColumn,MessageBox,Message,Icon,Tree,Dialog,Tooltip,Pagination } from 'element-ui'
    import { setToken,getCookie,getLevelName,getDate } from '~/utils/auth'
    
    Vue.use(Row)
    Vue.use(Col)
    Vue.use(Button)
    Vue.use(Input)
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Table)
    Vue.use(TableColumn)
    Vue.use(Icon)
    Vue.use(Tree)
    Vue.use(Dialog)
    Vue.use(Tooltip)
    Vue.use(Pagination);

    export default {
        head(){
            return {
                title: "我的日历"
            }
        },
        data () {
            return {
                tabName: '我的日历',
                filter: {
                    levels: '',
                    usIds: [],
                    bname:[]
                },
                category: {
                    name: '',
                    showTree: false,
                    data:[{
                        id: 0,
                        label: '全部',
                        children: [{    //预留children
                            id: 1,
                            label: '暂无数据'
                        }]
                    }]
                },
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                currentDay: 1,
                currentMonth: 1,
                currentYear: 1970,
                currentWeek: 1,
                days: [],
                dialogVisible: false,
                ownerFilter: {
                    pageNum: 1,
                    pageSize: 10,
                    deptId: ''
                },
                ownerOptions: [],
                ownerData: [],
                ownerPage: {
                    pageSizes: [10, 20, 50],    // 每页可选条数列表,
                    total: 0,
                    pageNum: 1
                },
                readOnly: false,
                seller: '',
                ownerRows: [],
                ownerSelection: [],
                userData: null,
                lastMonthData:null
            }
        },
        computed : {
            ...mapGetters({
                'calendarPlan': 'getCalendarPlan',
                'pageTabsList': 'getPageTabsList'
            }),
            filterData: function () {
                let data = {};
                data.levels = this.filter.levels;
                data.knowledgeIds = this.filter.usIds.join(',') || '';
                data.purchaseIds = this.filter.usIds.join(',') || '';
                data.dockIds = this.filter.usIds.join(',') || '';
                if(this.userData.leaderType == 1){
                    this.filter.usIds.length > 0 ? data.deptCode = null : data.deptCode = this.userData.deptCode;
                }else {
                    data.deptCode = null
                }
                //data.year = null;
                //data.month = null;
                data.planTimeBegin=''
                data.planTimeEnd=''
                return data
            },
            usIdString: function () {
                return this.filter.usIds.join(',') || ''
            },
            bnameString: function () {
                return this.filter.bname.join(',') || ''
            }
        },
        methods:{
            //搜索条件加入cookie
            setFilterCookie(){
                this.$store.commit('CALENDER_FILTER',{data:this.filter});
                this.$store.commit('CALENDER_CATEGORY',{data:this.category.name});
                this.$store.commit('CALENDER_SELLER',{data:this.seller});
            },
            ...mapActions([
                'fetchCalendarPlan'
            ]),
            initData (cur) {
                var date;
                if (cur) {
                    date = new Date(cur);
                } else {
                    date = new Date();
                }
                this.currentDay = date.getDate();
                this.currentYear = date.getFullYear();
                this.currentMonth = date.getMonth() + 1;
                this.currentWeek = date.getDay(); // 1...6,0
                if (this.currentWeek == 0) {
                    this.currentWeek = 7;
                }
                var str = this.formatDate(this.currentYear , this.currentMonth, this.currentDay);
                this.days.length = 0;
                // 今天是周日，放在第一行第7个位置，前面6个
                for (let i = this.currentWeek - 1; i >= 0; i--) {
                    let d = new Date(str);
                    d.setDate(d.getDate() - i);
                    this.days.push(this.dealDateData(d));
                }
                for (let i = 1; i <= 35 - this.currentWeek; i++) {
                    let d = new Date(str);
                    d.setDate(d.getDate() + i);
                    this.days.push(this.dealDateData(d));
                }

            },
            dealDateData(d) {
                let item = {};
                item.date = d.getDate();
                item.year = d.getFullYear();
                item.month = d.getMonth() + 1;
                item.allRecordCount = 0;
                item.energencyCount = 0;
                let len = this.calendarPlan.length;
                for (var i = 0;i < len; i++) {
                    if(this.calendarPlan[i].month === item.month && this.calendarPlan[i].day === item.date) {
                        item.allRecordCount = this.calendarPlan[i].allRecordCount;
                        item.energencyCount = this.calendarPlan[i].energencyCount;
                        break
                    }
                }
                let llen = this.lastMonthData.length;
                for (var i = 0;i < llen; i++) {
                    if(this.lastMonthData[i].month == item.month && this.lastMonthData[i].day == item.date) {
                        item.allRecordCount = this.lastMonthData[i].allRecordCount;
                        item.energencyCount = this.lastMonthData[i].energencyCount;
                        break
                    }
                }
                return item;
            },
            isOtherMonth(item){
                let d = new Date();
                if (item.month === this.currentMonth && item.year === this.currentYear) {
                    return false;
                }
                else {
                    return true
                }
            },
            isToday(item){
                let d = new Date();
                if (item.month === (d.getMonth() + 1) && item.date === d.getDate() && item.year === d.getFullYear()) {
                    return true;
                }
                else {
                    return false
                }
            },
            pickPre (year, month) {
                //  setDate(0); 上月最后一天
                //  setDate(-1); 上月倒数第二天
                //  setDate(dx) 参数dx为 上月最后一天的前后dx天
                let date = new Date(this.formatDate(year , month , 1));
                date.setDate(0);
                let newYear=date.getFullYear()
                let newMonth=date.getMonth() + 1
                let nMonth = date.getMonth() + 1;
                let days=this.getDaysInMonth(newYear,newMonth)
                if (newMonth<10) {
                	newMonth="0"+newMonth
                }
                this.filterData.planTimeBegin=newYear+"-"+newMonth+"-01 00:00:00";
                this.filterData.planTimeEnd=newYear+"-"+newMonth+"-"+days+" 23:59:59"
                this.handleLastMonthPlan(newYear,nMonth,date)
            },
            pickNext (year, month) {
                let date = new Date(this.formatDate(year , month , 1));
                date.setDate(35);
                let newYear=date.getFullYear()
                let newMonth=date.getMonth() + 1
                let nMonth = date.getMonth() + 1;
                let days=this.getDaysInMonth(newYear,newMonth)
                if (newMonth<10) {
                	newMonth="0"+newMonth
                }
                this.filterData.planTimeBegin=newYear+"-"+newMonth+"-01 00:00:00";
                this.filterData.planTimeEnd=newYear+"-"+newMonth+"-"+days+" 23:59:59"
                this.handleLastMonthPlan(newYear,nMonth,date)
            },
            pickToday () {
                let date = new Date();
                let newYear = date.getFullYear();
                let newMonth= date.getMonth() + 1;
                let nMonth = date.getMonth() + 1;
                let days=this.getDaysInMonth(newYear,newMonth)
                if (newMonth<10) {
                	newMonth="0"+newMonth
                }
                
                this.filterData.planTimeBegin=newYear+"-"+newMonth +"-01 00:00:00";
                this.filterData.planTimeEnd=newYear+"-"+newMonth +"-"+days+" 23:59:59"
                
                this.handleLastMonthPlan(newYear,nMonth,date)
            },
            handleLastMonthPlan(newYear,nMonth,date){
                let filterData = {};
                let lastMonth = null;
                let lastYear = null;
                let intMont = null;
                for ( let attr in this.filterData) {
                    filterData[attr] = this.filterData[attr];
                }

                if(nMonth == 1){
                    lastMonth = 12;
                    intMont = 12;
                    lastYear = newYear - 1;
                }else{
                    intMont = nMonth - 1;
                    lastMonth = nMonth - 1;
                    if (lastMonth<10) {
                        lastMonth="0" + lastMonth
                    }
                    lastYear = newYear;
                }

                let days=this.getDaysInMonth(lastYear,intMont)
                filterData.planTimeBegin = lastYear+"-"+lastMonth +"-01 00:00:00";
                filterData.planTimeEnd = lastYear+"-"+lastMonth +"-"+days+" 23:59:59"
                //获取上一个月数据
                this.$store.dispatch('getBrandCalendarPlan',filterData).then((res) => {
                    if (res.data.code == 0 && res.data.data) {
                        this.lastMonthData = res.data.data;
                        this.$store.dispatch('getBrandCalendarPlan',this.filterData).then((res) => {
                            if (res.data.code == 0 && res.data.data) {
                                this.$store.commit('dealCalendarPlan',{data: res.data.data})
                            }
                            this.initData(this.formatDate(date.getFullYear(),date.getMonth()+1,1));
                        })
                    }
                })
            },

            // 返回 类似 2016-01-02 格式的字符串
            formatDate (year,month,day){
                var y  = year;
                var m = month;
                if(m<10) m = "0" + m;
                var d = day;
                if(d<10) d = "0" + d;
                return y+"-"+m+"-"+d
            },
            
            //计算某一年某个月有多少天
            getDaysInMonth(year,month){
			    month = parseInt(month, 10);  
			  	var d= new Date(year, month, 0);  
			  	return d.getDate(); 
			},
            
            filterCustomerCalendar(year, month) {
            	let days=this.getDaysInMonth(year,month)
                let date = new Date(this.formatDate(year , month , 1));
                let nMonth = month;
                if (month<10) {
                	month="0"+month
                }
                this.filterData.planTimeBegin=year+"-"+month +"-01 00:00:00";
                this.filterData.planTimeEnd=year+"-"+month +"-"+days+" 23:59:59"
                this.handleLastMonthPlan(year,nMonth,date)

                this.setFilterCookie();
            },
            //客户分类选中回调
            handleCheckChange(data,checked) {
                this.category.name ='';
                var checkedId = this.$refs.searchTree.getCheckedKeys(data,true);
                var checkedName = [];
                if(checkedId.length == this.category.data[0].children.length) {
                    this.category.name = '全部'
                }else {
                    for(var i=0;i<checkedId.length;i++){
                        checkedName.push(getLevelName(checkedId[i]));
                    }
                    this.category.name = checkedName.join(' / ');
                }
                this.filter.levels = checkedId.join(',');
            },
            //隐藏客户分类
            treeBlurHide(){
                this.category.showTree = false;
            },
            closeOwnerDialog() {
                this.ownerFilter.deptId = '';
                this.ownerFilter.pageNum = 1;
                this.ownerFilter.pageSize = 10;
                this.dialogVisible = false;
            },
            searchOwner() {
                this.getUserOwnerData();
            },
            //获取销售员列表
            getUserOwnerData() {
                this.$store.dispatch('getUserOwnerData',this.ownerFilter)
                    .then((response) => {
                        if (response.data.code === 0) {
                            this.ownerData = response.data.data.list;
                            this.ownerPage.total = response.data.data.total;
                            this.ownerPage.pageNum = response.data.data.pageNum;
                        }
                    })
            },
            //销售员多选
            handleOwnerSelectionChange(selection) {
                let names = [];
                let ids = [];
                for (let i = 0; i < selection.length; i++) {
                    names.push(selection[i].name);
                    ids.push(selection[i].id)
                }
                this.ownerRows = ids;
                this.ownerSelection = names;
            },
            //销售员单选
            handleOwnerCurrentChange(currentRow) {
                this.ownerRows = currentRow.id;
                this.ownerCurrent = currentRow.name;
            },
            // 弹框销售员列表选择分页size
            ownerHandleCurrentChange(val) {
                this.ownerFilter.pageNum = val;
                this.getUserOwnerData();
            },
            ownerHandleSizeChange(val) {
                this.ownerFilter.pageSize = val;
                this.ownerFilter.pageNum = 1;
                this.getUserOwnerData();
            },
            onSubmit() {
                this.seller = this.ownerSelection.join(',');
                this.filter.usIds = this.ownerRows;
                this.filter.bname = this.ownerSelection;
                this.ownerSelection = [];
                this.ownerRows = [];
                this.dialogVisible = false;
            },
            cancelSeller() {
                this.seller = '';
                this.filter.usIds = [];
                this.dialogVisible = false;
            },
            getOwnerData() {
                this.dialogVisible = true;
                this.getUserOwnerData();
                this.getOwnerDeptment();
            },
            //获取销售员部门下拉框
            getOwnerDeptment() {
                this.$store.dispatch('getOwnerDeptment')
                    .then((response) => {
                        if (response.data.code === 0) {
                            this.ownerOptions = response.data.data;
                        }
                    })
            },
            getUserData() {
                this.$store.dispatch('getUserPersonalData')
                    .then((response) => {
                        var result = response.data;
                        if (result.code === 0) {
                            this.userData = response.data.data;
                            setToken('userData',response.data.data);
                            if(result.data && result.data.leaderType == 0) {
                                this.seller = result.data.name;
                                this.filter.usIds[0] = result.data.id;
                                this.readOnly = true;
                            }else {
                                this.readOnly = false;
                            }
                        }
                        this.pickToday();
                    })
                    .catch((error) => {
	        				
	                })
            },
        },
        created() {
            if(process.BROWSER_BUILD){
                //pageTab
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
        },
        mounted(){
            // 获取客户类别等级列表
            this.$store.dispatch('getSalesCategoryList')
                .then((response) => {
                    if(response.data && response.data.data ){
                        var data = response.data.data;
                        this.category.data[0].children=[];
                        for(var i=0;i< data.length;i++){
                            this.category.data[0].children.push({id: data[i].key , label : data[i].value});
                        }
                    }
                })
                .catch((error) => {
        				
                })

            //从cookie里取出filter数据
            // let parentUrl = getCookie('parentUrl');
            // if(parentUrl == 'calenderDetail'){}
            let filter = this.$store.getters.calenderFilter;
            let category = this.$store.getters.calenderCategory;
            let seller = this.$store.getters.calenderSeller;
            if(filter){
                this.filter = filter;
                this.category.name = category;
                this.seller = seller;
            }
            this.getUserData();
        }
    }
</script>

<style lang="scss">

    .my-calendar{
        padding-top: 15px;
        ul{
            list-style: none;
            margin: 0;
            padding: 0;
        }
        .calendar-menu{
            overflow: hidden;
            button{
                float: left;
            }
        }
        .calendar-menu-name{
            float: right;
            margin-left: 10px;
            font-size: 13px;
            line-height: 30px;
        }
        .calendar-menu-block{
            float: right;
            margin-left: 10px;
            width: 30px;
            height: 25px;
            margin-top: 2px;
            background-color: #ccc;
            &.all{
                background-color: #99CCFF;
             }
        }
        .calendar-table{
            margin: 20px auto 0;
            text-align: center;
            box-sizing: border-box;
            border-top: 1px solid #dfe6ec;
            border-left: 1px solid #dfe6ec;
            li{
                position: relative;
                height: 40px;
                float: left;
                width: 14.28%;
                box-sizing: border-box;
                border-right: 1px solid #dfe6ec;
                border-bottom: 1px solid #dfe6ec;
                line-height: 40px;
            }
        }
        .calendar-head{
            overflow: hidden;
            li{
                background-color: #eef1f6;
            }
        }
        .calendar-body{
            overflow: hidden;
            li{
                height: 60px;
                line-height: 60px;
            }
            .countCon{
                overflow: hidden;
                width: 100%;
                height: 25px;
                margin-top: 25px;
            }
            .todoList,.todoList2{
                float: left;
                width: 50%;
                background-color: #99CCFF;
                color: white;
                font-size: 18px;
                font-weight: 600;
                text-align: center;
                line-height: 25px;
                cursor: pointer;
                &.full{
                    width: 100%;
                 }
            }
            .todoList2{
                background-color: #CCCCCC;
            }
        }
        .calendar-row{
            &:hover{
                background-color: antiquewhite;
             }
            span{
                position: absolute;
                right: 5px;
                top:5px;
                line-height: 14px;
            }
        }
        .otherMonth{
            color: gainsboro;
        }
        .today{
            color: red;
        }
        .calendar-tip{
            padding: 10px 0 0;
            color: #999;
            text-align: center;
            font-size: 13px;
        }
        .calendar-search{
            margin-top: 5px;
        }
    }
    .calendar-page{
        height: 100%;
        .top_close{
            float: left;
            margin-left: 20px;
            margin-top: 20px;
        }
        .top_close, .top_save{
            margin: 0 20px;
        }
        .top_save {
            float: right;
        }
    }
</style>